﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Articles.LinqDynamicWhere
{
    public static class Samples
    {
        /// <summary>
        /// get a csv string of files in a folder
        /// </summary>
        /// <param name="folder"></param>
        /// <returns></returns>
        public static string GetStringOfAllFiles(string folder,SearchOption option)
        {
            string allfiles = "";

            new DirectoryInfo(folder).GetFiles("*.*", option)
                .ToList<FileInfo>()
                .ForEach(f => allfiles += f.FullName.Substring(folder.Length) + ", ");

            return allfiles.Substring(0,allfiles.LastIndexOf(","));
        }

        public static List<FileInfo> ClassicSearchInFiles
            (string folder, string keyword, string extension,SearchOption option)
        {
            DirectoryInfo dir = new DirectoryInfo(folder);
            string search = "";
            //if keyword is defined then create the pattern *keyword*
            if (!string.IsNullOrEmpty(keyword))
                search += "*" + keyword + "*";
            //if keyword is not defined add a wildcard for name
            else 
                search += "*";
            
            //if extension is defined then add it (it must be in .txt for exemple)
            if (!string.IsNullOrEmpty(extension))
                search += extension;
            //else add a wildcard
            else
                search += ".*";
            
            return dir.GetFiles(search, option).ToList<FileInfo>();
        }


        public static List<FileInfo> GetFilesByTypeAndKeyword(string _folder, string ext, string name)
        {
            DirectoryInfo folder = new DirectoryInfo(_folder);
            List<FileInfo> files =
                    (from f in folder.GetFiles("*.*", SearchOption.AllDirectories)
                     where (string.IsNullOrEmpty(ext) || f.Extension == ext) &&
                           (string.IsNullOrEmpty(name) || f.Name.Contains(name))
                     select f).ToList<FileInfo>();
            return files;
        }
    }
}
